package com.example.calcite.memory;

import com.example.calcite.ITable;
import org.apache.calcite.DataContext;
import org.apache.calcite.linq4j.Enumerable;
import org.apache.calcite.linq4j.Linq4j;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.schema.impl.AbstractTable;
import org.apache.calcite.sql.type.SqlTypeName;

import java.util.ArrayList;
import java.util.List;

public class MemoryTable extends AbstractTable implements ITable {
    private final String[] columns;
    private final List<Object[]> rows = new ArrayList<>();

    public MemoryTable(String[] columns) {
        this.columns = columns;
    }

    @Override
    public String[] getColumns() {
        return columns;
    }

    @Override
    public void insert(Object... values) {
        if (values.length != columns.length) {
            throw new IllegalArgumentException("Number of values does not match number of columns");
        }
        rows.add(values);
    }

    public List<Object[]> getRows() {
        return rows;
    }

    @Override
    public RelDataType getRowType(RelDataTypeFactory typeFactory) {
        RelDataTypeFactory.Builder builder = typeFactory.builder();
        for (String column : columns) {
            if (column.equalsIgnoreCase("ID")) {
                builder.add(column, typeFactory.createSqlType(SqlTypeName.INTEGER));
            } else if (column.equalsIgnoreCase("AGE")) {
                builder.add(column, typeFactory.createSqlType(SqlTypeName.INTEGER));
            } else if (column.equalsIgnoreCase("SALARY")) {
                builder.add(column, typeFactory.createSqlType(SqlTypeName.DECIMAL));
            } else {
                builder.add(column, typeFactory.createSqlType(SqlTypeName.VARCHAR));
            }
        }
        return builder.build();
    }

    /*@Override
    public Enumerable<Object[]> scan(DataContext root) {
        return Linq4j.asEnumerable(rows);
    }*/

    @Override
    public Enumerable<Object[]> scan(DataContext root, List<RexNode> filters) {
//        return Linq4j.asEnumerable(rows).where();
        return null;
    }
}